package com.fyh.filter;

import com.fyh.constant.JwtConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class JwtAuthFilter implements GlobalFilter {

    // 定义不需要JWT验证的路径 在经过网关后去除/api后的路径
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/user/login",
            "/user/register",
            "/chat/chatting"
    );
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        // 检查是否在白名单中
        log.info("请求路径：{}", path);
        if (WHITE_LIST.stream().anyMatch(path::startsWith)) {
            return chain.filter(exchange);
        }


        String token = exchange.getRequest().getHeaders().getFirst("Token");
        // 检查token是否存在
        if (token == null) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            log.info("未携带JWT令牌");
            return exchange.getResponse().setComplete();
        }

        // 验证token
        Long userId = validateToken(token);
        if(userId == null){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            log.info("JWT令牌校验失败");
            return exchange.getResponse().setComplete();
        }
        else{
            exchange.getRequest().mutate().header("userId", userId.toString());
        }

        if(path.startsWith("/employer") && !validateEmployerToken(token)){
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            log.info("未授权访问");
            return exchange.getResponse().setComplete();
        }

        if(path.startsWith("/candidate") && !validateCandidateToken(token)){
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            log.info("未授权访问");
            return exchange.getResponse().setComplete();
        }
        log.info("已授权访问");
        return chain.filter(exchange);
    }

    private boolean validateEmployerToken(String token) {
        try {
            log.info("开始验证JWT令牌：{}", token);
            Claims claims = Jwts.parser()
                    .setSigningKey(JwtConstant.SIGNATRUE)
                    .parseClaimsJws(token)
                    .getBody();
            if(!"employer".equals(claims.get("userType"))){
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private boolean validateCandidateToken(String token) {
        try {
            log.info("开始验证JWT令牌：{}", token);
            Claims claims = Jwts.parser()
                    .setSigningKey(JwtConstant.SIGNATRUE)
                    .parseClaimsJws(token)
                    .getBody();
            if(!"candidate".equals(claims.get("userType"))){
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private Long validateToken(String token) {
        try {
            log.info("开始验证JWT令牌：{}", token);
            Claims claims = Jwts.parser()
                    .setSigningKey(JwtConstant.SIGNATRUE)
                    .parseClaimsJws(token)
                    .getBody();
            Long userId = ((Integer) claims.get("userId")).longValue();
            return userId;
        } catch (Exception e) {
            return null;
        }
    }
}
